<!-- 出库 -->
<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" :size="curDrawerSize" :close-on-click-modal="isReadOnly">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">出库</div>
			</div>
		</template>

		<template #default>
			<el-container class="zs-drawer-container">
				<el-scrollbar class="zs-drawer-content">
					<!-- card1 -->
					<div class="zs-align-center zs-space-bottom" id="sm-drawer-demo-card-01">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">物料信息</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<HsForm :filed-list="storageOutFiledList" ref="infoForm" @selectChange="selectChange" @remoteMethod="remoteMethod" :isDisabled="isReadOnly"></HsForm>
					</div>
					<!-- card2 -->
					<CreateUserInfo ref="createDataRef" userLabel="操作人：" timeLabel="操作时间：" title="操作信息" id="create-user-info" />
				</el-scrollbar>
				<hsDocWrapper :nodeList="curNodeList" />
			</el-container>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<div>
				<el-button class="zs-btn-md zs-btn-primary" @click="confirmFn">提交</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
	import EffectAndFailureTime from '@/components/effectAndFailureTime.vue';
	import CreateUserInfo from '@/components/createUserInfo.vue';
	import HsForm from '@/components/hsForm.vue';
	import { storageOutFiledList } from '@/config/form/supplies.js';
	import { storageOutApi } from '@/api/supplies.js';
	import { userSearchApi } from '@/api/common.js';
	import { ElMessageBox, ElMessage } from 'element-plus';
	import { ref, reactive, watch, nextTick } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';
	import { setFormSelectOptions } from '@/utils/formEvent';
	import { numPositiveNumber } from '@/utils/formRules';

	const route = useRoute();

	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		currentRow: { type: Object },
	});

	let store = useStore();
	let dictObj = store.getters.getDictObj(['PROPERTY_CERTIFICATE_TYPE']);
	const curDrawerSize = ref(store.state.uiDrawerSize);

	const emit = defineEmits(['close']);

	let isShowDrawer = ref(props.isShow);

	const curNodeList = ref([
		{ name: '物料信息', id: 'sm-drawer-demo-card-01' },
		{ name: '操作信息', id: 'create-user-info' },
	]);

	const infoForm = ref();
	let createDataRef = ref();

	watch(
		() => props.isShow,
		(newVal, oldVal) => {
			isShowDrawer.value = newVal;
			nextTick(() => {
				newVal && initForm();
			});
		},
	);

	//提交
	const confirmFn = () => {
		ElMessageBox.confirm('需由领取人工单确认，是否确定提交?', {
			confirmButtonText: '是',
			cancelButtonText: '否',
			type: 'warning',
		})
			.then(() => {
				doConfirm();
			})
			.catch(() => {});
	};

	const doConfirm = async () => {
		let modleInfo = await infoForm.value.validateForm();
		if (!modleInfo) return;
		let params = Object.assign(modleInfo);
		params.materielId = props.currentRow.materielId;
		params.materielIntoId = props.currentRow.id;
		let res = await storageOutApi(params);
		if (res.data.code == 200) {
			ElMessage({
				message: '提交成功',
				type: 'success',
			});
			isShowDrawer.value = false;
			emit('close', { isShow: false, isRefresh: true });
		}
	};

	//关闭抽屉
	const handleClose = done => {
		emit('close', { isShow: false });
		done();
	};

	//初始化表单项
	const initForm = () => {
		let userInfo = JSON.parse(localStorage.getItem('userInfo'));
		storageOutFiledList.forEach(item => {
			if (item.bindFieldName == 'outNum') {
				item.rules = [
					{ validator: judgeOutNum(), trigger: ['change', 'blur'] },
					{ validator: numPositiveNumber(), trigger: ['change', 'blur'] },
				];
			}
		});
		nextTick(() => {
			props.handleType == 'add' && infoForm.value.resetFields();
			infoForm.value.setFiledSource('outTime', new Date().getTime());
			createDataRef.value.setData({ createTime: new Date().getTime(), createUserName: userInfo.user.realName });
		});
	};

	// 出库数量不能大于可用数
	function judgeOutNum() {
		return (rule, value, callback) => {
			let outNum = Number(props.currentRow.outNum)
			if (!props.currentRow.outNum || outNum == 0) {
				callback(new Error('无可用数量'));
			} else if (value > outNum) {
				callback(new Error('出库数量不能大于可用数量'));
			} else {
				callback();
			}
		};
	}

	//表单关联
	const selectChange = data => {};

	//联想查询
	const remoteMethod = data => {
		if (data.filedName == 'receiver') {
			getSearchList(data.remoteVal);
		}
	};

	//用户列表
	const getSearchList = async name => {
		if (!name) return;
		const phoneNumberPattern = /^1[3-9]\d{9}$/;
		let nameParams = phoneNumberPattern.test(name) ? { phoneNumber: name } : { realName: name };
		let params = Object.assign({ pageSize: 10000, pageNum: 1 }, nameParams);
		let res = await userSearchApi(params);
		res.data.data.userList.forEach(item => {
			item.name = `${item.realName}(${item.phoneNum})`;
		});
		setFormSelectOptions(storageOutFiledList, 'receiver', res.data.data.userList);
	};
</script>
